import { px2remPx } from '@/utils/flexble'
import { cloneDeep, debounce, isArray, isNumber, isPlainObject } from 'lodash-es'
import { onMounted, onUnmounted, ref, type Ref } from 'vue'

export default function usePx2rempx<T>(px: number | number[] | any): { remPx: Ref<T> } {
  const remPx = ref()

  function changeValue() {
    if (isArray(px)) {
      remPx.value = px.map((value) => px2remPx(value))
    } else if (isPlainObject(px)) {
      const newRemPx = cloneDeep(px)
      Object.keys(px).forEach((key) => {
        newRemPx[key] = px2remPx(px[key] as number)
      })
      remPx.value = newRemPx
    } else if (isNumber(px)) {
      remPx.value = px2remPx(px)
    }
  }

  changeValue()

  const outerWidth = ref(window.outerWidth)

  const outerHeight = ref(window.outerHeight)

  const eventHandler = debounce(() => {
    changeValue()

    setTimeout(() => {
      outerWidth.value = window.outerWidth

      outerHeight.value = window.outerHeight
    }, 250)
  }, 150)

  onMounted(() => {
    window.addEventListener('resize', eventHandler)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', eventHandler)
  })

  return { remPx }
}
